package kyssion.leetcode.num51_100;

import kyssion.leetcode.util.ShowUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class code89_格雷编码 {
    public static void main(String[] args) {
        List<Integer> list = new code89_格雷编码().grayCode(3);
        ShowUtil.showList(list,true);
    }


    public List<Integer> grayCode(int n) {
        if(n<=0){
            return Collections.singletonList(0);
        }
        List<Integer> list = new ArrayList<>();
        list.add(0);
        list.add(1);
        for (int a=2;a<=n;a++){
            int base = 1<<a-1;
            for(int b = list.size()-1;b>=0;b--){
                list.add(list.get(b)+base);
            }
        }
        return list;
    }

    public List<Integer> grayCode2(int n) {
        /**
         关键是搞清楚格雷编码的生成过程, G(i) = i ^ (i/2);
         如 n = 3:
         G(0) = 000,
         G(1) = 1 ^ 0 = 001 ^ 000 = 001
         G(2) = 2 ^ 1 = 010 ^ 001 = 011
         G(3) = 3 ^ 1 = 011 ^ 001 = 010
         G(4) = 4 ^ 2 = 100 ^ 010 = 110
         G(5) = 5 ^ 2 = 101 ^ 010 = 111
         G(6) = 6 ^ 3 = 110 ^ 011 = 101
         G(7) = 7 ^ 3 = 111 ^ 011 = 100
         **/
        List<Integer> ret = new ArrayList<>();
        for(int i = 0; i < 1<<n; ++i)
            ret.add(i ^ i>>1);
        return ret;
    }
}
